﻿console.log("This is a popup!")


var button = document.getElementById("sendButton");

// 加载已保存的内容
if (localStorage.getItem('nodePath')) {
  document.getElementById('nodePath').value = localStorage.getItem('nodePath');
}
if (localStorage.getItem('projectName')) {
  document.getElementById('projectName').value = localStorage.getItem('projectName');
}
if (localStorage.getItem('contentInput')) {
  document.getElementById('contentInput').value = localStorage.getItem('contentInput');
}

function sendContent() {
  const content = document.getElementById('contentInput').value;
  const projectName = document.getElementById('projectName').value;
  const nodePath = document.getElementById('nodePath').value;

  // 清空输入框
  document.getElementById('nodePath').value = '';
  document.getElementById('projectName').value = '';
  document.getElementById('contentInput').value = '';

  // 清除LocalStorage中的对应值
  localStorage.removeItem('nodePath');
  localStorage.removeItem('projectName');
  localStorage.removeItem('contentInput');

  // 显示加载提示
  showLoadingOverlay();

  chrome.runtime.sendMessage({ action: 'getContent', content: content, projectName: projectName, nodePath: nodePath }, function (response) {
    console.log('Content sent:', response);


    // 隐藏加载提示
    hideLoadingOverlay();

    // 发送一个额外的消息给background脚本，通知其隐藏页面
    chrome.runtime.sendMessage({ action: 'hidePage' });
  });
}

function showLoadingOverlay() {
  loadingOverlay.classList.remove('hidden');
}

function hideLoadingOverlay() {
  loadingOverlay.classList.add('hidden');
}

// 保存输入内容到LocalStorage
document.getElementById('nodePath').addEventListener('blur', function () {
  localStorage.setItem('nodePath', this.value);
});

document.getElementById('projectName').addEventListener('blur', function () {
  localStorage.setItem('projectName', this.value);
});

document.getElementById('contentInput').addEventListener('blur', function () {
  localStorage.setItem('contentInput', this.value);
});

// 添加点击事件监听器
button.addEventListener("click", function () {
  sendContent();
}, false);


// 监听背景脚本的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === 'hidePage') {
    document.body.classList.add('hidden');
    // 如果需要的话，可以在这里添加更多的逻辑，例如通知用户页面已隐藏
    console.log('Page hidden by background script.');
  }
});
